﻿using System;
using System.Collections.Generic;
using System.Linq;
using Model;
using DBUtility;
using MySql.Data.MySqlClient;

namespace DAL
{
    public class BomRepository
    {
        // 添加BOM
        public int AddBom(Bom bom)
        {
            string sql = @"INSERT INTO bom 
                            (BomVersion, SerialNumber) 
                           VALUES 
                            (@BomVersion, @SerialNumber)";

            MySqlParameter[] parameters = {
                new MySqlParameter("@BomVersion", bom.BomVersion),
                new MySqlParameter("@SerialNumber", bom.SerialNumber)
            };

            return DBHelper.ExecuteNonQuery(sql, parameters);
        }

        // 删除BOM
        public int DeleteBom(int bomId)
        {
            string sql = "DELETE FROM bom WHERE BomId = @BomId";
            MySqlParameter[] parameters = { new MySqlParameter("@BomId", bomId) };
            return DBHelper.ExecuteNonQuery(sql, parameters);
        }

        // 更新BOM信息
        public int UpdateBom(Bom bom)
        {
            string sql = @"UPDATE bom 
                            SET BomVersion = @BomVersion, 
                                SerialNumber = @SerialNumber 
                          WHERE BomId = @BomId";

            MySqlParameter[] parameters = {
                new MySqlParameter("@BomVersion", bom.BomVersion),
                new MySqlParameter("@SerialNumber", bom.SerialNumber),
                new MySqlParameter("@BomId", bom.BomId)
            };

            return DBHelper.ExecuteNonQuery(sql, parameters);
        }

        // 查询所有BOM
        public List<Bom> GetAllBoms()
        {
            string sql = "SELECT * FROM bom";
            return DBHelper.ExecuteQuery(sql, null, MapBom);
        }

        // 查询单个BOM
        public Bom GetBomById(int bomId)
        {
            string sql = "SELECT * FROM bom WHERE BomId = @BomId";
            MySqlParameter[] parameters = { new MySqlParameter("@BomId", bomId) };
            var boms = DBHelper.ExecuteQuery(sql, parameters, MapBom);
            return boms.FirstOrDefault();
        }

        // 映射数据库查询结果到 Bom 对象
        private Bom MapBom(MySqlDataReader reader)
        {
            return new Bom
            {
                BomId = (int)reader["BomId"],
                BomVersion = reader["BomVersion"].ToString(),
                SerialNumber = reader["SerialNumber"] is DBNull ? null : (int?)reader["SerialNumber"]
            };
        }
    }
}